<template>
  <div>
    <el-page-header :icon="null" title="企业门户网站管理系统">
      <template #content>
        <span class="text-large font-600 mr-3"> 个人中心 </span>
      </template>
    </el-page-header>

    <el-row :gutter="20" class="el-row">
      <el-col :span="8">
        <el-card class="box-card">
          <!-- 用户头像不显示 -->
          <el-avatar :size="100" :src="avatarUrl" />
          <h3>{{ $store.state.userInfo.username }}</h3>
          <h5>{{ $store.state.userInfo.role === 1 ? '管理员' : '编辑' }}</h5>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>
          <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="select" style="width: 100%;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="简介" prop="introduction">
              <el-input v-model="userForm.introduction" type="textarea" />
            </el-form-item>

            <!-- 上传头像 -->
            <el-form-item label="头像" prop="avatar">
              <el-upload class="avatar-uploader" action="" :show-file-list="false" :auto-upload="false"
                :on-change="handleChange">
                <img v-if="userForm.avatar" :src="uploadAvatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <!--  更新按钮  -->
            <el-form-item>
              <el-button type="primary" @click="submitForm">更新</el-button>
            </el-form-item>

          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { useStore } from "vuex"
import { computed, ref, reactive } from "vue"
import { Plus } from '@element-plus/icons-vue'
import axios from "axios"
import { ElMessage } from "element-plus"

const store = useStore()
const userFormRef = ref()
const { id, username, gender, introduction, avatar } = store.state.userInfo

// 数据响应式对象
const userForm = reactive({
  // 数据是从 store 中解构出来的
  id,
  username,
  gender,
  introduction,
  avatar,
  file: null      // 存储一个file字段，不影响表单提交
})

// 用户验证规则
const userFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度大于3小于10', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  intoduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }]
})

// 性别
const options = [
  {
    label: '保密',
    value: 0
  },
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 2
  },
]

// 图像地址显示（store里面的）
const avatarUrl = computed(() => {
  return store.state.userInfo.avatar ? store.state.userInfo.avatar : `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`
})

// 图像回显处理
const uploadAvatar = computed(() => {
  return userForm.avatar ? userForm.avatar : `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`
})

// 选择完图片之后回调（每次选择完图片之后的回调）
const handleChange = (file) => {
  // 回显参数
  userForm.avatar = URL.createObjectURL(file.raw)
  // 存储到form表单，提交到后端
  userForm.file = file.raw
}
/**
 * 更新用户信息
 */
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      const parmas = new FormData()
      for (let i in userForm) {
        parmas.append(i, userForm[i])
      }
      await axios.post("/adminapi/user/upload", parmas, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(res => {
        if (res.data.status !== 0) {
          return ElMessage.error('更新用户信息失败！')
        }
        console.log(res.data.data)
        store.commit("changeUserInfo", res.data.data)
        ElMessage.success('更新用户信息成功！')
      })
    } else {
      return false
    }
  })
}

</script>

<style lang="scss" scoped>
.el-row {
  margin-top: 20px;

  .box-card {
    text-align: center;
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

::v-deep .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>

